/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "pluginloader.h"
#include "debug.h"

z_plugin z_plugin_init(char *path)
{
	z_plugin tmp;
	tmp.path = path;
	tmp.so = NULL;
	tmp.namer = NULL;
	tmp.sic = NULL;
	tmp.nsigs = 0;
	tmp.handler = NULL;
	return tmp;
}

int z_plugin_release(z_plugin p)
{
	return 0;
}

int z_plugin_load(z_plugin *p)
{
	printf("loading %s...\n", p->path);
	p->so = dlopen(p->path, RTLD_LAZY);
	if (p->so == NULL)
	{
		Z_WARNING("cannot load plugin (%s) ((%s))", p->path, dlerror());
		return 1;
	}

	p->namer = dlsym(p->so, "_z_pluginapi_namer");
	p->sic = dlsym(p->so, "_z_pluginapi_sic");
	p->sic(NULL, &p->nsigs);
	p->handler = dlsym(p->so, "_z_pluginapi_handler");

	return 0;
}

int z_plugin_unload(z_plugin *p)
{
	dlclose(p->so);
	p->so = NULL;
	return 0;
}

char *z_plugin_name(z_plugin *p)
{
	return p->namer();
}

int z_plugin_max_sig(z_plugin *p)
{
	return p->nsigs;
}

int z_plugin_sig(z_plugin *p, char *s)
{
	int tmp;
	return p->sic(s, &tmp);
}

z_data z_plugin_call(z_plugin *p, int s, z_data d)
{
	return p->handler(s, d);
}
